//
//  VolatileGetter.m
//  Staff
//
//  Created by caiyao on 1/14/15.
//
//

#import "VolatileGetter.h"
#import "ShareData.h"
#import "NSString+SBJSON.h"

@implementation VolatileGetter

- (void)excute {
    NSString *key = [self.command.functionParamsDic objectForKey:@"key"];
    
    if (self.command.callbackJS == nil || key == nil)
    {
        // params is missing fail to handle
        [self excuteNonHookFoundCallback];
        return;
    }
    
    // get value of volatile web cache
    NSString *volatileCacheValue = [[ShareData shareInstance] vGetter:key];
    DebugLog(@"volatile getter value=%@", volatileCacheValue);
    if(volatileCacheValue == nil)
    {
        volatileCacheValue = @"";
    }
    
    BOOL isJSON =NO;
    
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    DebugLog(@"start try to paser the string as json object.");
    NSDictionary *proxyInfo= [volatileCacheValue JSONValue];
    DebugLog(@"end try to paser the string as json object.");
    if (proxyInfo != nil)
    {
        isJSON =YES;
    }
    [pool release];
    
    NSString *jsChange= [NSString stringWithString:volatileCacheValue];
    
    if (isJSON == YES)
    {
        // proxy recevie is a json object
        jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
        jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        
        [self excuteCallBackJSWithParameters:jsChange];
    }
    else
    {
        // excute callbackJS
        [self excuteCallBackJSWithParameters:volatileCacheValue];

    }
}

@end
